﻿using PSDClientService.SystemSettings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSDClientListener
{
    public class KeepAliveManager
    {
        private ClientListener context;
        private System.Threading.Thread checkTread = null;
        private bool running = false;
        public KeepAliveManager(ClientListener ctx)
        {
            context = ctx;
        }

        public void Init()
        {

        }


        public void Start()
        {
            running = true;
            checkTread = new System.Threading.Thread(new System.Threading.ThreadStart(CheckAlive));
            checkTread.Start();
        }

        public void Stop()
        {
            try
            {
                running = false;
                checkTread.Abort();
            }
            catch { }
        }


        public void KeepAlive(DateTime time)
        {
            context.PSDClientState.AliveTime = time;
        }

        public void CheckAlive()
        {
            while (running)
            {
                if ((DateTime.Now - context.PSDClientState.AliveTime).TotalSeconds > AppSettings.Setting.DownloadKeepAliveTimeout * 60)
                {
                    context.RestartPSDClientManager.RestartPSDClientService(RestartType.Timeout);
                }

                System.Threading.Thread.Sleep(1000 * 60);
            }
        }
    }
}
